/*
 * @Author: Qimu
 * @Date: 2020-04-16 14:23:21
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-02 20:00:00
 * @Description: file content
 * @FilePath: \vue-admin-koa2\koa2_api\module\utlis\tools.js
 */
const md5 = require('md5') // md5加密
const jwt = require('jsonwebtoken') // 签发Token

const tools = {

  /*md5加密
  * @param {String} str [密码字符串] 
  */
  md5(string) {
    return md5(string);
  },

  /* 格林尼治时间(GMT)转时间戳
   * @param {time} str [GMT字符串] 
   */
  GMTtoStr(time) {
    const date = new Date(time);
    const Year = date.getFullYear();
    const Month = date.getMonth() + 1 < 10 ? `0${(date.getMonth() + 1)}` : date.getMonth() + 1;
    const Day = date.getDate() < 10 ? `0${(date.getDate())}` : date.getDate();
    const Hours = date.getHours() < 10 ? `0${(date.getHours())}` : date.getHours();
    const Minutes = date.getMinutes() < 10 ? `0${(date.getMinutes())}` : date.getMinutes();
    const Seconds = date.getSeconds() < 10 ? `0${(date.getSeconds())}` : date.getSeconds();
    const dateLog = `${Year}-${Month}-${Day}`;
    const timeLog = `${Hours}:${Minutes}:${Seconds}`;
    return `${dateLog} ${timeLog}`
  },

  /* 电话号码验证方法
  * @param {String} str [电话号字符串] 
  */
  phone(string) {
    const phoneCode = /^(13|14|15|17|18|19)\d{9}$/;
    if (phoneCode.test(string)) return true;
  },

  /*邮箱证方法
  * @param {String} str [邮箱字符串] 
  */
  email(string) {
    const email = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    if (email.test(string)) return true;
  },

  /*token签名
  * @param {payload} obj [用户信息] 
  * @param {secret} str [秘钥] 
  * @param {expiresIn} obj [token过期时间] 
  */
  signToken(payload, secret, expiresIn) {
    return new Promise((resolve, reject) => {
      jwt.sign(payload, secret, { expiresIn }, (err, res) => {
        err ? reject(err) : resolve(res)
      })
    })
  },
}

exports = module.exports = tools;